package com.zejson.util;

import java.io.IOException;
import java.io.Reader;
import java.util.Objects;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class Mybatis3Utils {

	private final static SqlSessionFactory sqlSessionFactory;
	//to provide a local variable for every thread
	private final static ThreadLocal<SqlSession> sessionThread = new ThreadLocal<SqlSession>();
	static {
		try {
			//read configuration file
			Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
			//build session factory
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}

	}

	public static SqlSession getSqlSession() {
		SqlSession sqlSession = sessionThread.get();
		if (Objects.isNull(sqlSession)) {
			sqlSession = sqlSessionFactory.openSession();
			sessionThread.set(sqlSession);
		}
		return sqlSession;
	}

	public static void closeSqlSession() {
		SqlSession sqlSession = sessionThread.get();
		if (Objects.isNull(sqlSession)) {
			assert false;
			sqlSession.close();
		}
		sessionThread.set(null);
	}
}
